<!DOCTYPE html>
<html>
<head>
    <title>WebSocket JSON 通信示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 10px;
            height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
        }
        .message {
            margin: 5px 0;
            padding: 8px;
            border-radius: 4px;
        }
        .server-message {
            background-color: #e3f2fd;
            text-align: left;
        }
        .client-message {
            background-color: #e8f5e9;
            text-align: right;
        }
        .status {
            color: #666;
            font-style: italic;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
    <h1>WebSocket JSON 通信示例</h1>
    <div class="status" id="status">连接中...</div>
    <div class="container" id="messages"></div>

    <script>
        // 连接到WebSocket服务器
        const ws = new WebSocket('ws://localhost:8765');
        let clientCounter = 0;
        let messageInterval;
        
        // 获取DOM元素
        const statusElement = document.getElementById('status');
        const messagesElement = document.getElementById('messages');
        
        // 连接成功建立
        ws.onopen = function() {
            statusElement.textContent = '已连接到服务器，正在交换消息...';
            statusElement.style.color = 'green';
            
            // 每1秒向服务器发送一次消息
            messageInterval = setInterval(() => {
                if (ws.readyState === WebSocket.OPEN) {
                    // 构建JSON消息
                    const message = {
                        type: "client_message",
                        timestamp: new Date().toISOString(),
                        counter: clientCounter,
                        message: `这是客户端发送的第 ${clientCounter} 条消息`
                    };
                    
                    // 发送JSON字符串
                    ws.send(JSON.stringify(message));
                    
                    // 在页面上显示客户端发送的消息
                    displayMessage(message, 'client-message');
                    
                    clientCounter++;
                }
            }, 1000);
        };
        
        // 收到服务器消息
        ws.onmessage = function(event) {
            try {
                // 解析JSON消息
                const message = JSON.parse(event.data);
                // 在页面上显示服务器发送的消息
                displayMessage(message, 'server-message');
            } catch (e) {
                console.error('解析JSON失败:', e);
                displayMessage({ message: '收到无效的JSON消息: ' + event.data }, 'server-message');
            }
        };
        
        // 连接关闭
        ws.onclose = function() {
            statusElement.textContent = '连接已关闭';
            statusElement.style.color = 'red';
            clearInterval(messageInterval);
        };
        
        // 连接错误
        ws.onerror = function(error) {
            statusElement.textContent = `发生错误: ${error}`;
            statusElement.style.color = 'red';
        };
        
        // 在页面上显示消息
        function displayMessage(message, className) {
            const messageElement = document.createElement('div');
            messageElement.className = `message ${className}`;
            
            // 格式化消息显示
            messageElement.innerHTML = `
                <strong>${new Date(message.timestamp).toLocaleTimeString()}</strong><br>
                ${message.message}<br>
                <small>计数器: ${message.counter}</small>
            `;
            
            messagesElement.appendChild(messageElement);
            // 滚动到底部
            messagesElement.scrollTop = messagesElement.scrollHeight;
        }
    </script>
</body>
</html>
